$(function () {
	var productInfo = {};
	var selectPriceId = "";
	// 申购规则
	let buyRule=''
	function getUrlParam(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
		var r = window.location.search.substr(1).match(reg); //匹配目标参数
		if (r != null) return unescape(r[2]);
		return null; //返回参数值
	}
	let buySetData=null;
	let useSetData=null
	// 购买和使用的数量
	let buyNum=0
	let useNum=0
	// 产品id
	let productId =getUrlParam('productId')
	// 产品最后的价格
	let customerProductPrice=0

	//获取数据产品详情
	function getDataInfo() {
		$.ajax({
       timeout:30000,
			url: window.Http + "/customer/product/info",
			type: 'GET',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data: { productId: getUrlParam('productId') },
			success: function (res) {
				if (res.code === 200) {
					// console.log('JSON.parse(buyRule)', JSON.parse(buyRule))
					// console.log('buyRule', buyRule)
					let status = {
						'-1': '保存',
						'0': '正常',
						'1': '故障',
						'2': '未审核',
						'3': '未测试'
					}
					let buyStatus = {
						'-1': '申购状态',
						'0': '可用次数',
						'2': '可用记录数',
						'3': '可用字节数',
						'4': '可用时间'
					}
					let buyType = {
						'-1': '未申购',
						'0': res.data.canUseNumber,
						'2': res.data.canUseRecords,
						'3': res.data.canUseBytes,
						'4': res.data.canUseTime
					}
					// 产品类型
					let productType={
						'3':'算法产品',
						'5':'应用产品'
					}
					productInfo = res.data;
					$("#dataTitle").text(res.data.productName);
					$("#createTime").text(res.data.createTime.slice(0, 10));
					$("#status").text(status[`${res.data.status}`]);
					$('#buyCount').html(res.data.buyCount);
					$('#visitCount').html(res.data.visitCount);
					$('#buyStatus').html(buyStatus[`${res.data.buyStatus}`]);
					$('#sharedType').html(res.data.buyRuleId == -1 ? '无条件共享' : '有条件共享');
					$('#buyType').html(buyType[`${res.data.buyStatus}`])
					$('#brief').html(res.data.brief);
					$('#detail').html(res.data.detail)
					$('#createBy').html(res.data.createBy);
					$('#productName').html(res.data.productName);
					$('#productType').text(productType[res.data.sourceType])
					//priceLable(res.data.dataproductPriceList);
					if(res.data.dataproductExtendList == 0){
						$("#isTry").text("不可以");
						$(".applyTry").addClass("disabledNone");
					}else{
						$("#isTry").text("可以");
						$(".applyTry").removeClass("disabledNone");
					}
					if(res.data.buyRuleId != -1){
						$(".pricingTypeBox").removeClass("disabledNone");
						$(".useTypeBox").removeClass("disabledNone");
						buyRule=res.data.buyRule?.priceRule;
						buySetData=JSON.parse(buyRule).buy
						console.log('buySetData', buySetData)
						 useSetData = JSON.parse(buyRule).use;
						console.log('useSetData', useSetData)
						priceLabel(buySetData);
						useTypeLabel(useSetData);
					}else{
						$(".unconditionalBox").removeClass("disabledNone");
					}
				}
			}
		});

	}
	getDataInfo()

	let buyType={
		'访问期限':4,
		'访问次数':0,
		'按记录数访问':2
	}
	let useType={
		'使用期限':0,
		'使用次数':4
	}
	// 申购产品
	$("#submitShopping").click(function () {
		let buyDataProductForm={
			"customerBillingType": 0,
			"customerBillingTypeLocal": 0,
			"customerCanUseDay": 0,
			"customerCanUseDayLocal": 0,
			"customerCanUseNumber": 0,
			"customerCanUseNumberLocal": 0,
			"customerCanUseRecords": 0,
			"customerProductPrice": 0,
			"productId": ""
		}
		buyDataProductForm.productId=productId
		buyDataProductForm.customerProductPrice=customerProductPrice;
		// 获取当前选中的购买方式和使用方式
		//console.log('购买方式', $('#priceLableBox .price.active').text())
		// 购买方式
		buyDataProductForm.customerBillingType=buyType[$('#priceLableBox .price.active').text()]
		switch (buyDataProductForm.customerBillingType) {
			case 0:
				buyDataProductForm.customerCanUseNumber=buyNum;
				break;
			case 2:
				buyDataProductForm.customerCanUseRecords=buyNum;
				break;
			case 4:
				buyDataProductForm.customerCanUseDay=buyNum;
				break;
		}
		// console.log('customerBillingType', customerBillingType)
		buyDataProductForm.customerBillingTypeLocal=useType[$('#useLableBox .price.active').text()]
		switch (buyDataProductForm.customerBillingTypeLocal) {
			case 0:
				buyDataProductForm.customerCanUseNumberLocal=buyNum;
				break;
			case 4:
				buyDataProductForm.customerCanUseDayLocal=buyNum;
				break;
		}

		$.ajax({
       timeout:30000,
			url: window.Http + "/orderProduct/buyProduct",
			type: 'POST',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data: JSON.stringify(buyDataProductForm),
			contentType: 'application/json;charset=utf-8',
			success: function (res) {
				if (res.code === 200) {
					layer.msg(res.msg);
				} else if (res.code === 401) {
					layer.alert('未登录，请前往登录界面进行登录', {
						skin: 'layui-layer-lan',
						closeBtn: 0,
						anim: 1 //动画类型
					}, function () {
						window.location.href = './login.html';
					});
				} else {
					layer.msg(res.msg);
				}
			},
			error: function (err) {
				layer.msg(err.msg);
			}
		})


	});


	$('.decrement').click(function () {
		let productNum = $('.itxt').val();
		if(productNum <= 1){
			$('.itxt').val(1);
		}else{
			$('.itxt').val(--productNum);
		}
	})
	$('.increment').click(function () {
		let productNum = $('.itxt').val();
		if(productNum < 1){
			$('.itxt').val(1);
		}else{
			$('.itxt').val(++productNum);
		}
	})

	// 点击加入产品袋
	$('.addShoppingCart').on('click', function () {
		let buyDataProductForm={
			"customerBillingType": 0,
			"customerBillingTypeLocal": 0,
			"customerCanUseDay": 0,
			"customerCanUseDayLocal": 0,
			"customerCanUseNumber": 0,
			"customerCanUseNumberLocal": 0,
			"customerCanUseRecords": 0,
			"customerProductPrice": 0,
			"productId": 0
		}
		buyDataProductForm.productId=productId
		buyDataProductForm.customerProductPrice=customerProductPrice;
		// 获取当前选中的购买方式和使用方式
		console.log('购买方式', $('#priceLableBox .price.active').text())
		// 购买方式
		buyDataProductForm.customerBillingType=buyType[$('#priceLableBox .price.active').text()]
		switch (buyDataProductForm.customerBillingType) {
			case 0:
				buyDataProductForm.customerCanUseNumber=buyNum;
				break;
			case 2:
				buyDataProductForm.customerCanUseRecords=buyNum;
				break;
			case 4:
				buyDataProductForm.customerCanUseDay=buyNum;
				break;
		}
		// console.log('customerBillingType', customerBillingType)
		buyDataProductForm.customerBillingTypeLocal=useType[$('#useLableBox .price.active').text()]
		switch (buyDataProductForm.customerBillingTypeLocal) {
			case 0:
				buyDataProductForm.customerCanUseNumberLocal=buyNum;
				break;
			case 4:
				buyDataProductForm.customerCanUseDayLocal=buyNum;
				break;
		}
		$.ajax({
       timeout:30000,
			url: window.Http + "/cart/save",
			type: 'POST',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data: JSON.stringify(buyDataProductForm),
			contentType: 'application/json;charset=utf-8',
			success: function (res) {
				if (res.code === 200) {
					layer.msg('成功加入产品袋', { icon: 1 });
				}else if (res.code === 401) {
					layer.alert('未登录，请前往登录界面进行登录', {
						skin: 'layui-layer-lan',
						closeBtn: 0,
						anim: 1 //动画类型
					}, function () {
						window.location.href = './login.html';
					});
				} else {
					layer.msg(res.msg);
				}
			},
			error: function (err) {
				layer.msg(err.msg);
			}
		})


	})
	//执行算法产品
	$("#executeProduct").click(function () {
		window.productId = getUrlParam('productId');
		layer.open({
			type: 2,
			title: "执行算法产品",
			area: ['800px', '480px'],
			content: "./popupPage/useAlgProductPop.html"
		});
	})
	
	//试用申请
	$(".applyTry").click(function () {
		window.productId = getUrlParam('productId');
		layer.open({
			type: 2,
			title: "试用申请",
			area: ['800px', '480px'],
			content: "./popupPage/applyTryPop.html"
		});
	})

	// 查看数据通道
	$('.viewSource').click(function () {
		window.location.href = './dataStoreDetial.html?sourceId=' + productInfo.sourceId;
	})


	//计价方式显示
	function priceLabel(buySetData) {
		for (let key in buySetData) {
			if (key !== "priceWay") {
				let newHtml = `<span class="price">${buySetData[key].tip}</span>`
				// }else if(buySetData[key].priceway == "add"){
				// 	addHtml += `<span class="price">${buySetData[key].tip}</span>`
				// }
			$("#priceLableBox").append(newHtml);
			}
		}
	}
	//使用方式显示
	function useTypeLabel(useSetData) {
		for (let key in useSetData) {
			if (key !== "priceWay"){
				let newHtml = `<span class="price">${useSetData[key].tip}</span>`
				$("#useLableBox").append(newHtml);
			}
		}
	}

	let buyTotalPrice= 0,useTotalPrice = 0;
	//计算申购总价
	function countBuyTotalPrice(data,nums){
		// console.log('计算价格进度条', data,nums)
		if(data.calcway == "average"){
			console.log('计算价格进度条',nums)
			//平均数公式
			//价格 = 最低价+（（数值-最小值）/（最大值-最小值））*（最高价-最低价）；
			buyTotalPrice = data.minPrice +((nums - data.minValue)/(data.maxValue - data.minValue))*(data.maxPrice - data.minPrice);
			buyTotalPrice = buyTotalPrice.toFixed(2);
			console.log('buyTotalPrice', buyTotalPrice)
			let totalPrice = (buyTotalPrice*100 + useTotalPrice*100)/100;
			$('#totalPrice').text(totalPrice);
		}else if(data.calcway == "log"){
			console.log('计算价格进度条', data,nums)
			//对数公式
			//价格 = 最低价+（（Math.log10(数值)-Math.log10(最小值)）/（Math.log10（最大值）-Math.log10(最小值)））*（最高价-最低价）；
			let buyTotalPrice = data.minPrice +((Math.log10(nums) - Math.log10(data.minValue))/(Math.log10(data.maxValue) - Math.log10(data.minValue)))*(data.maxPrice - data.minPrice);
			buyTotalPrice = buyTotalPrice.toFixed(2);
			let totalPrice = (buyTotalPrice*100 + useTotalPrice*100)/100;
			$('#totalPrice').text(totalPrice);
		}
	}
	//计算使用总价
	function countUseTotalPrice(data,nums){
		console.log('useTotalPrice', useTotalPrice)
		if(data.calcway == "average"){
			//平均数公式
			//价格 = 最低价+（（数值-最小值）/（最大值-最小值））*（最高价-最低价）；
			useTotalPrice = data.minPrice +((nums - data.minValue)/(data.maxValue - data.minValue))*(data.maxPrice - data.minPrice);
			useTotalPrice = useTotalPrice.toFixed(2);
			let totalPrice = (buyTotalPrice*100 + useTotalPrice*100)/100;
			$('#totalPrice').text(totalPrice);
		}else if(data.calcway == "log"){
			//对数公式
			//价格 = 最低价+（（Math.log10(数值)-Math.log10(最小值)）/（Math.log10（最大值）-Math.log10(最小值)））*（最高价-最低价）；
			let useTotalPrice = data.minPrice +((Math.log10(nums) - Math.log10(data.minValue))/(Math.log10(data.maxValue) - Math.log10(data.minValue)))*(data.maxPrice - data.minPrice);
			useTotalPrice = useTotalPrice.toFixed(2);
			let totalPrice = (buyTotalPrice*100 + useTotalPrice*100)/100;
			customerProductPrice=totalPrice;
			$('#totalPrice').text(totalPrice);
		}
	}
	//选择价格方式
	$("#priceLableBox").delegate('.price', 'click', function (e) {
		$(this).addClass("active").siblings(".price").removeClass("active");
		let tipVal = $(this).text();
		if(tipVal === "访问期限"){
			$("#buyCalculateUnit").text("(天数)");
		}else if(tipVal === "按记录数访问"){
			$("#buyCalculateUnit").text("（KB)");
		}else{
			$("#buyCalculateUnit").text("(次数)");
		}

		for (let key in buySetData) {

			if (buySetData.priceWay === "new" && tipVal == buySetData[key].tip){

				//数量范围
				layui.use('slider', function(){
				  var $ = layui.$,slider = layui.slider;
				  slider.render({
				    elem: '#buySlideNumber',
					min: buySetData[key].minValue, //最小值
					max: buySetData[key].maxValue, //最大值
					change: function(values){
						buyNum=values
						countBuyTotalPrice(buySetData[key],values)
					}
				  });
				})
				console.log('buySetData[key].minPrice', buySetData[key].minPrice)
				//价格范围
				$("#buyMinprice").text(buySetData[key].minPrice);
				$("#buyMaxprice").text(buySetData[key].maxPrice);
			}
		}
	})
	//选择使用方式
	$("#useLableBox").delegate('.price', 'click', function (e) {
		$(this).addClass("active").siblings(".price").removeClass("active");
		let tipVal = $(this).text();
		if(tipVal == "使用期限"){
			$("#useCalculateUnit").text("(天数)");
		}else{
			$("#useCalculateUnit").text("(次数)");
		}
		let currentData;
		for (let key in useSetData) {
			if (useSetData.priceWay === "add" && tipVal ==useSetData[key].tip){
				currentData = useSetData[key];
			}
		}
		//数量范围
		if(currentData){
			layui.use('slider', function(){
			  var $ = layui.$,slider = layui.slider;
			  slider.render({
			    elem: '#useSlideNumber',
				min: currentData.minValue, //最小值
				max: currentData.maxValue, //最大值
				change: function(values){
					useNum=values;
					countUseTotalPrice(currentData,values)
				}
			  });
			})
			//价格范围
			$("#useMinprice").text(currentData.minPrice);
			$("#useMaxprice").text(currentData.maxPrice);
		}else{
			$("#useSlideNumber").empty();
			//价格范围
			$("#useMinprice").text(0);
			$("#useMaxprice").text(0);
		}

	})

	//评价
	layui.use(['laypage', 'layer'], function(){
		var laypage = layui.laypage,layer = layui.layer;
	    laypage.render({
	      elem: 'evaluatePage'
	      ,count: 100
	      ,layout: ['count', 'prev', 'page', 'next']
	      ,jump: function(obj){
	        console.log(obj)
	      }
	    });
	})
})
